const {
	usersModel,
	model
} = require('../model/users.js');
const md5 = require('md5');
let upload = multer({ storage: storage });
let imageName = '';
class Users {
	async list(req, res) {
		let {
			pageSize,
			currentPage,
			field,
			fieldVal
		} = req.query;
		pageSize = parseInt(pageSize) > 0 ? parseInt(pageSize) : 10;
		currentPage = parseInt(currentPage) > 0 ? parseInt(currentPage) : 1;
		const offset = (currentPage - 1) * pageSize;
		let where = {};
		if (field && fieldVal) {
			where[field] = {
				$like: `%${fieldVal}%`
			};
		}
		let total = await usersModel.findOne({
			where,
			attributes: [[model.fn('COUNT', model.col('id')), 'count']],
			raw: true
		});
		total = total.count;
		const ret = await usersModel.findAll({
			where,
			offset,
			limit: pageSize
		}).catch((ret) => {
			res.status(404);
			res.send({
				error: '获取数据失败',
				data: null
			});
		})
		setTimeout(() => {
			res.send({
				error: null,
				data: {
					total,
					currentPage,
					pageSize,
					rows: ret,
				}
			})
		}, 0);
	}
	async one(req, res) {
		const id = req.params.id;
		const ret = await usersModel.findOne({
			raw: true,
			where: {
				id
			}
		}).catch(() => {
			res.status(404)
			res.send({
				data: null,
				error: '数据查询失败'
			})
			return
		})
		res.send({
			error: null,
			data: ret
		});
	}
	add(req, res) {
		usersModel.create(req.body).then((ret) => {
			res.status(200)
			res.send(ret)
		}).catch((ret) => {
			console.log(ret.errors)
			res.status(404)
			res.send(ret.errors[0].message)
		});
	}
	edit(req, res) {
		const id = req.params.id;
		if (!/^[0-9]+$/.test(id)) {
			res.status(404);
			res.send({
				error: '路由参数必须是数字',
				data: null
			})
			return;
		}
		usersModel.update(req.body, {
			where: {
				id: {
					$eq: id
				}
			}
		}).then((ret) => {
			res.status(200)
			res.send({
				error: null,
				data: null
			})
		}).catch((ret) => {
			res.status(404);
			res.send({
				error: '更新失败',
				data: null
			})
		});
	}
	del(req, res) {
		const id = req.params.id;
		if (!/^[0-9]+$/.test(id)) {
			res.status(404);
			res.send('路由参数必须是数字')
			return;
		}
		usersModel.destroy({
			where: {
				id: {
					$eq: id
				}
			}
		}).then((ret) => {
			res.status(200);
			res.send({
				error: '删除成功',
				data: null
			})
		}).catch((ret) => {
			res.status(404);
			res.send('删除失败')
		});
	}
	regist(req, res) {
		(new Users).add(req, res)
	}
	login(req, res) {
		const {
			body
		} = req;
		if (!body.username) {
			res.status(404);
			res.send({
				error: '请输入用户名和密码',
				data: null
			})
			return;
		}
		usersModel.findOne({
			where: {
				...body
			},
			raw: true
		}).then((ret) => {
			const {
				id,
				username,
				email,
				phone,
				gender
			} = ret
			if (username) {
				req.session.logged = true;
				req.session.userInfo = {
					id,
					username,
					email,
					phone,
					gender
				};
				res.send({
					error: null,
					data: ret
				});
			} else {
				res.status(404);
				res.send({
					error: '登陆失败'
				})
			}
		}).catch((ret) => {
			console.log(ret)
			res.status(404);
			res.send({
				error: '请先登陆'
			})
		})
	}
	logout(req, res) {
		if (!req.session.logged) {
			res.status(200);
			res.send({
				error: '请先登陆'
			})
			return;
		}
		req.session.destroy((error) => {
			if (!error) {
				res.status(200);
				res.send({
					error: null,
					data: null
				})
			} else {
				res.status(404);
				res.send({
					error: '注销失败'
				})
			}
		})
	}
	avatar(req, res) {
		//上传文件
		let storage = multer.diskStorage({
			destination: function (req, file, cb) {
				cb(null, '../../static/images');
			},

			/*以时间戳命名的文件*/
			filename: function (req, file, cb) {
				cb(null, `${Date.now()}-${file.originalname}`)
			}

			/*filename: function (req, file, cb) {
				cb(null, `${file.originalname}`)
			}*/
		});
		console.log(req.body);
		res.send({
			error: null,
			data: '什么鬼'
		})
	}
	isLogin(req, res) {
		res.send({
			error: null,
			data: req.session.logged ? 1 : 0
		})
	}
	async exists(req, res) {
		const {
			field,
			value
		} = req.params;
		let where = {}
		where[field] = value;
		const ret = await usersModel.findOne({
			where,
		});
		if (ret) {
			res.send(true);
		} else {
			res.send(false)
		}
	}
}
module.exports = new Users();


// app.all('/images', upload.array('imgfile', 40), (req, res, next) => {
// 	let files = req.files;
// 	if (!files[0]) {
// 		res.send('error');
// 		//在此地加上return 纯属于防止express报错,因为send和end结束之后都会调用return
// 		return 'error'
// 	} else {
// 		console.log(files[0].filename);
// 		imageName = files[0].filename;
// 		res.send('success');
// 		return 'success'
// 	}
// });

// //需改用户头像路径
// app.all('/imagesUpdate', (req, res, next) => {
// 	let id = req.query.id;
// 	//将传来的ID转换为mongodb的ObjectId,需要引入mogoose
// 	let _id = mongoose.Types.ObjectId(id);
// 	console.log(id);
// 	user.update({ "_id": _id }, { $set: { headPicture: 'http://localhost:3000/images/' + imageName } }, { upsert: true, multi: false }, (err, data) => {
// 		console.log(imageName, '&&&&&&&&&&&&&&&&&&&&&&&&&');
// 		res.send(imageName);
// 	});
// });
